package com.java.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.mapper.RecordMapper;
import com.java.po.Record;
import com.java.po.RecordMap;
import com.java.service.RecordService;
import com.java.tool.AjaxJson;

public class RecordServiceImpl implements RecordService{

	@Autowired
	private RecordMapper recordMapper;
	private AjaxJson ajaxJson;
	
	public RecordServiceImpl(){
		@SuppressWarnings("resource")
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
		recordMapper = (RecordMapper) applicationContext.getBean("recordMapper");		
		ajaxJson = new AjaxJson();
	}
	
	public void cleanAjaxJson(){
		ajaxJson.setData("");
		ajaxJson.setTotal(0);
		ajaxJson.setMessage("");
	}
	
	@Override
	public AjaxJson insertRecord(Record record) throws Exception {
		// TODO Auto-generated method stub
		int flag = recordMapper.insertRecord(record);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson deleteRecord(Record record) throws Exception {
		// TODO Auto-generated method stub
		int flag = recordMapper.deleteRecord(record);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson updateRecord(Record record) throws Exception {
		// TODO Auto-generated method stub
		int flag = recordMapper.updateRecord(record);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson findAllRecord(RecordMap recordMap) throws Exception {
		// TODO Auto-generated method stub
		Record record =new Record();
		int page = recordMap.getPage();
		int pageSize = recordMap.getPageSize();
		if(recordMap.getRecord()!=null){
			record = recordMap.getRecord();
		}
		PageHelper.startPage(page,pageSize);
		List<Record> list = recordMapper.findAllRecord(record);
		PageInfo<Record> pageInfo = new PageInfo<>(list);
		ajaxJson.setData(pageInfo.getList());
		ajaxJson.setTotal((int)pageInfo.getTotal());
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson findRecordByid(Record record) throws Exception {
		// TODO Auto-generated method stub
	    record=recordMapper.findRecordByid(record);
		ajaxJson.setData(record);
		ajaxJson.setMessage("success");
		ajaxJson.setTotal(1);
		return ajaxJson;
	}

}
